<template>
    <div>
        <el-card class="box-card">
            <el-button icon="plus" type="primary" @click="showDialogFrom(undefined)">添加品牌</el-button>
            <el-button type="danger" icon="delete" @click="deleteSelectTrademark">删除</el-button>

            <el-table border stripe :data="tableData" class="table-main" ref="tableRef"
                @selection-change="handleSelectionChange">
                <el-table-column align="center" type="selection" width="55" />
                <el-table-column align="center" label="序号" width="80" type="index" />
                <el-table-column align="center" prop="tmName" label="品牌名称" width="150">
                    <template #="{ row }">
                        <span style="color: #409eff;">{{ row.tmName }}</span>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="品牌LOGO">
                    <template #default="{ row }">
                        <div class="image__preview">
                            <el-image :src="row.logoUrl" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2"
                                :preview-src-list="[row.logoUrl]" :initial-index="4" fit="cover" preview-teleported
                                hide-on-click-modal>
                                <template #placeholder>
                                    <div>Loading<span class="dot">...</span></div>
                                </template>
                                <template #error>
                                    <div class="image-slot"><i-ep-Picture /></div>
                                </template>

                            </el-image>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column align="center" label="品牌操作" width="240">
                    <template #default="{ row }">
                        <el-button type="primary" icon="edit" @click="showDialogFrom(row)">编辑</el-button>
                        <el-button type="danger" icon="delete" @click="deleteTrademark(row.id)">删除</el-button>
                    </template>

                </el-table-column>
            </el-table>

            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[3, 5, 10, 20, 30, 40]" layout="prev, pager, next, jumper, ->, sizes, total" :total="total"
                @change="fetchData" />
        </el-card>

        <el-dialog v-model="dialogFormVisible" :title=dialogTitle @closed="closeDialog">
            <el-form :model="form" label-width="auto" :rules="rules" ref="ruleFormRef" status-icon scroll-to-error>
                <el-form-item label="品牌名称" prop="tmName">
                    <el-input v-model="form.tmName" style="width: 80%;" placeholder="请输入品牌名称"></el-input>
                </el-form-item>
                <el-form-item label="品牌LOGO" prop="logoUrl">
                    <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <i-ep-Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>

            </el-form>
            <template #footer>
                <el-button type="primary" @click="confirm(ruleFormRef)">确认</el-button>
                <el-button @click=" dialogFormVisible = false">取消</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang='ts' name="Trademark">

import { reqHasTrademark, reqSaveTrademark, reqUpdateTrademark, reqDeleteTrademark } from '@/api/product/trademark'
import type { Trademark } from '@/api/product/trademark/type'
import type { ResponseData } from '@/api/type';
import { Action, ElMessage, ElMessageBox, ElTable, FormInstance, FormRules, UploadProps } from 'element-plus';

let tableData = ref<Trademark[]>()
let currentPage = ref<number>(1)
let pageSize = ref<number>(5)
let total = ref<number>(0)
const tableRef = ref<InstanceType<typeof ElTable> | null>(null);

let dialogFormVisible = ref<boolean>(false)

let form = reactive<Trademark>({
    tmName: '',
    logoUrl: ''
})

let ruleFormRef = ref<FormInstance>();

let selectIds = ref<number[]>([]);

const rules = ref<FormRules<Trademark>>({
    tmName: [
        { required: true, message: '品牌不能空', trigger: 'blur' },
    ],
    logoUrl: [
        { required: true, message: '请上传品牌LOGO' },
    ],
});

// 缓存对话框标题
const dialogTitle = computed(() => form.id ? '编辑品牌' : '添加品牌');

const confirm = async (ruleFormRef: FormInstance | undefined) => {

    if (!ruleFormRef) return
    await ruleFormRef.validate(async (valid, fields) => {
        if (!valid) {
            console.log('error submit!', fields);
            return;
        }
        if (form.id) {
            reqUpdateTrademark(form).then(() => {
                ElMessage.success('修改品牌成功')
                dialogFormVisible.value = false
                fetchData()
            }).catch((error: ResponseData<String>) => {
                ElMessage.error(`修改品牌失败。${error.message}`)
            })
        } else {
            reqSaveTrademark(form).then(() => {
                ElMessage.success('添加品牌成功')
                dialogFormVisible.value = false
                fetchData()
            }).catch((error: ResponseData<String>) => {
                ElMessage.error(`添加品牌失败。${error.message}`)
            })
        }

    })
}

const handleSelectionChange = (newSelection: Trademark[]) => {
    const validIds = newSelection
        .map(item => item.id)
        .filter(id => id !== undefined) as number[];
    selectIds.value = validIds
}

const deleteSelectTrademark = () => {
    if (selectIds.value.length === 0) {
        ElMessage.error('请选择要删除的品牌')
        return
    }
    ElMessageBox.confirm(
        '确定删除吗？',
        '删除提示',
        {
            distinguishCancelAndClose: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    ).then(() => {
        ElMessage.success(`删除成功[${selectIds.value.join(',')}]`)
        fetchData()
    }).catch((action: Action) => {
        console.log("🚀 ~ deletekSelectTrademark ~ action:", action)
    })
}

const deleteTrademark = async (id: number) => {
    try {
        await ElMessageBox.confirm(
            '确定删除吗？',
            '删除提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
            }
        )
        if (id === undefined) return
        reqDeleteTrademark(id).then(() => {
            fetchData()
            ElMessage.success('删除成功')
        }).catch((error: ResponseData<String>) => {
            ElMessage.error(`删除失败。${error.message}`)
        })
    } catch (action) {
        console.log("🚀 ~ deleteTrademark ~ action:", action)
    }
}

const closeDialog = () => {
    ruleFormRef.value?.resetFields()
    Object.assign(form, {
        tmName: '',
        logoUrl: '',
        id: undefined
    })
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response) => {
    if (response.code === 200) {
        form.logoUrl = response.data
        ruleFormRef.value?.clearValidate('logoUrl')
    } else {
        ElMessage.error('图片上传失败{}', response.message)
    }
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (!rawFile.type.startsWith('image/')) {
        ElMessage.error('请上传图片文件!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('图片文件大小不能超过2MB!')
        return false
    }
    return true
}

const fetchData = async () => {
    reqHasTrademark(currentPage.value, pageSize.value).then(result => {
        total.value = result.data.total
        tableData.value = result.data.records
        if (tableRef.value) {
            tableRef.value.setScrollTop(0);
        }
    }).catch((error: ResponseData<String>) => {
        ElMessage.error(`获取品牌列表失败 ${error.message}`)
    });
}

function showDialogFrom(row: Trademark | undefined) {
    dialogFormVisible.value = true
    if (!row) return
    Object.assign(form, row)
}

onMounted(() => {
    fetchData()
})
</script>

<style scoped lang="scss">
.table-main {
    height: calc(100vh - $base-tabbar-height - 170px);
    margin: 10px 0px;
}

.avatar-uploader .avatar {
    width: 178px;
    // height: 178px;
    display: block;
}

.image__preview {
    position: relative;
    display: inline-block;
    width: 100px;
    height: 100px;
    overflow: hidden;
    text-align: center;

    .image-slot {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 100px;
        height: 100px;
        background: var(--el-fill-color-light);
        color: var(--el-text-color-secondary);
        font-size: 30px;
    }


    .image-slot .el-icon {
        font-size: 30px;

        .dot {
            animation: dot 2s infinite steps(3, start);
            overflow: hidden;
            text-align: center;

        }
    }
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>